package uk.ac.ebi.bioinvindex.utils.mock;

import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import uk.ac.ebi.bioinvindex.dao.ejb3.InvestigationEJB3DAO;
import uk.ac.ebi.bioinvindex.dao.ejb3.StudyEJB3DAO;
import uk.ac.ebi.bioinvindex.model.impl.StudyImpl;
import uk.ac.ebi.bioinvindex.model.impl.InvestigationImpl;
import uk.ac.ebi.bioinvindex.model.impl.processing.AssayImpl;


import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import static java.lang.System.out;
import java.util.Collection;

/**
 * An helper class used to create an Hibernate Search Index from the current database.
 * Issue this command to run this utility:
 *
 *   mvn -Dtest=indexTestSet test
 *
 * @author brandizi
 */
public class TestSetIndexBuilder
{

	private EntityManager entityManager;

	public TestSetIndexBuilder ()
	{
	}


	public void indexAllStudies ()
	{
		EntityManager entityManager = getEntityManager ();
		EntityTransaction tnx = entityManager.getTransaction();

		StudyEJB3DAO dao = new StudyEJB3DAO(entityManager);
		FullTextEntityManager fullTxtEm = Search.createFullTextEntityManager ( entityManager );
		tnx.begin ();
		for ( StudyImpl study: dao.getAll() ) {
			out.println ( "\t\tIndexing Study #" + study.getId () );
			fullTxtEm.index ( study );
			fullTxtEm.index(study.getDesign());
			Collection<AssayImpl> assays = study.getAssays();
			for (AssayImpl assay : assays) {
				fullTxtEm.index(assay);
			}
		}
		tnx.commit ();
	}


	public void indexAllInvestigations ()
	{
		EntityManager entityManager = getEntityManager ();
		EntityTransaction tnx = entityManager.getTransaction();

		InvestigationEJB3DAO dao = new InvestigationEJB3DAO();
		dao.setEntityManager ( entityManager );
		FullTextEntityManager fullTxtEm = Search.createFullTextEntityManager ( entityManager );
		tnx.begin ();
		for ( InvestigationImpl inv: dao.getAll () ) {
			out.println ( "\t\tIndexing Investigation #" + inv.getId() );
			fullTxtEm.index ( inv );
		}
		tnx.commit ();
	}


	public void indexAll ()
	{
		this.indexAllStudies ();
		this.indexAllInvestigations ();
	}


	public EntityManager getEntityManager () {
		return this.entityManager;
	}

	public void setEntityManager (EntityManager entityManager) {
		this.entityManager = entityManager;
	}



//	public static void main ( String args [] ) {
//		out.println ( "\n\n*** Getting the Entity Manager" );
//		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("BIIEntityManager");
//		EntityManager entityManager = entityManagerFactory.createEntityManager();
//
//		out.println ( "\n\n*** Done! Now reindexing" );
//		TestSetIndexBuilder builder = new TestSetIndexBuilder ();
//		builder.setEntityManager ( entityManager );
//		builder.indexAllStudies ();
//
//		out.println ( "\n\n*** That's all!" );
//	}

}
